package com.vonchange.headb.utils.template;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.vonchange.headb.utils.string.HStringUtils;

/**
 *简单模板实现
 * @author von_change@163.com
 * @date 2015-6-14 下午10:44:07
 */
public class HTpl {
	/**
	 * 字符串占位符替换
	 * @param tplStr
	 * @param data
	 * @return 替换过的String
	 */
	public static String tplByMap(String tplStr, Map<String, Object> data) {
		Matcher m = Pattern.compile("\\{([\\w\\.]*)\\}").matcher(tplStr);
		List<String> patternList = new ArrayList<String>();
		List<String> replaceStrList = new ArrayList<String>();
		while (m.find()) {
			String group = m.group();
			patternList.add(group);
			group = group.replaceAll("\\{|\\}", "");
			String value = "";
			if (null != data.get(group)) {
				value = String.valueOf(data.get(group));
			}
			replaceStrList.add(value);
			//tplStr = tplStr.replace(m.group(), value);
		}
		tplStr=HStringUtils.replaceEach(tplStr, patternList.toArray(new String[patternList.size()]), replaceStrList.toArray(new String[replaceStrList.size()]));
		return tplStr;
	}

	/**
	 * 数字替换{0}
	 * @param str
	 * @param arr
	 * @return String
	 */
	public static String tplByArgs(String str, String... arr) {
		Matcher m = Pattern.compile("\\{(\\d)\\}").matcher(str);
		while (m.find()) {
			str = str.replace(m.group(), arr[Integer.parseInt(m.group(1))]);
		}
		return str;
	}


}
